package services

import (
	"encoding/json"
	"gorm.io/gorm"
	"mygo/app/models"
	"mygo/app/tools"
	"strings"
)

func HandelHyxian(forecast *models.Forecast, time string, db *gorm.DB) {
	var foreList models.ForeList
	db.Where("code = ?", "wzhy").First(&foreList)
	var foreDetail models.ForeDetailJson
	if db.Where("foreListId = ? AND time = ? AND state != ?", foreList.Id, time, "0").First(&foreDetail).RowsAffected > 0 {
		var hyData = models.Forecast{}
		json.Unmarshal(foreDetail.Data, &hyData)
		for i, report := range forecast.Reports {
			if i == 0 {
				for _, row := range report.Data {
					if tools.TwoCorrelation(row[0].Value, []string{"南麂", "北麂"}) {
						row[2].Value = hyData.Reports[1].Data[3][1].Value
					}
					if tools.TwoCorrelation(row[0].Value, []string{"洞头", "苍南"}) {
						row[2].Value = hyData.Reports[1].Data[2][1].Value
					}
					if tools.TwoCorrelation(row[0].Value, []string{"瑞安", "平阳", "龙港"}) {
						njValueArr := tools.GetNumFloat64(hyData.Reports[1].Data[3][1].Value)
						var newValueArr []float64
						//当[南麂列岛（市）/2]<=0.5时，x=0.1；[南麂列岛（市）/2]<=1.0时，x=0.2；[南麂列岛（市）/2]<=1.6时，x=0.3；[南麂列岛（市）/2]>1.6时，x=[南麂列岛（市）/4]；
						for _, v := range njValueArr {
							if v/2 <= 0.5 {
								newValueArr = append(newValueArr, 0.1+v/2)
							} else if v/2 <= 1.0 {
								newValueArr = append(newValueArr, 0.2+v/2)
							} else if v/2 <= 1.6 {
								newValueArr = append(newValueArr, 0.3+v/2)
							} else {
								newValueArr = append(newValueArr, v/4+v/2)
							}
						}
						row[2].Value = tools.ReplaceFloat64(hyData.Reports[1].Data[3][1].Value, newValueArr)
					}

					if tools.TwoCorrelation(row[0].Value, "龙湾") {
						row[2].Value = hyData.Reports[1].Data[1][1].Value
					}
					if tools.TwoCorrelation(row[0].Value, "乐清") {
						row[2].Value = hyData.Reports[1].Data[4][1].Value
					}

					//去除row[2].Value中的 ”明天“，”后天“
					row[2].Value = strings.Replace(row[2].Value, "明天", "", -1)
					row[2].Value = strings.Replace(row[2].Value, "后天", "", -1)
				}
			}
		}
	}

	var foreListLast models.ForeList
	db.Where("code = ?", "hyxian").First(&foreListLast)
	var foreDetailLast models.ForeDetailJson
	//	时间倒叙排序第一个
	if db.Where("foreListId = ? AND state != ?", foreListLast.Id, "0").Order("time desc").First(&foreDetailLast).RowsAffected > 0 {
		//	预填row[4].Value为上一次的预报值
		var hyDataLast = models.Forecast{}
		_ = json.Unmarshal(foreDetailLast.Data, &hyDataLast)
		for i, report := range forecast.Reports {
			if i == 0 {
				for rowIdx, row := range report.Data {
					row[4].Value = hyDataLast.Reports[0].Data[rowIdx][4].Value
				}
			}
		}
	}

}
